import 'package:base/main.dart';
import 'package:framework/core/base_logic.dart';
import 'package:framework/core/base_view_model.dart';
import 'package:framework/data/datasources/discover_local_repository.dart';
import 'package:framework/data/model/domain_bean.dart';
import 'package:framework/data/repositories/discover_repository.dart';
import 'package:module_discover/enums/domain_type_enum.dart';
import 'package:module_discover/pages/filter_domain/view_model/filter_preview_vm.dart';
import 'package:module_discover/pages/filter_domain/view_model/filter_state_vm.dart';
import 'package:module_discover/pages/filter_domain/view_model/select_input_vm.dart';
import 'package:module_discover/pages/model/Domain_info_model.dart';
import 'package:module_discover/pages/model/domain_title_model.dart';
import 'package:module_discover/pages/model/filter_model.dart';
import 'package:module_discover/utils/dis_cons.dart';
import 'package:module_discover/utils/dis_time_util.dart';
import 'package:module_discover/utils/filter_converter.dart';

class FilterDomainLogic extends BaseLogic {
  /// 数据源
  final DiscoverRepository _repository = DiscoverLocalRepository();

  /// 回显数据
  Map<String, Map<String, DomainInfoModel>>? chooseBackMaps;

  /// VM
  late FilterStateVM filterStateVM;
  late FilterPreviewVM filterPreviewVM;
  late SelectInputVM selectInputVM;

  /// 标题分类列表
  final RxList<Rx<DomainTitleModel>> domainTitles =
      <Rx<DomainTitleModel>>[].obs;

  /// 当前选中分类索引
  final selectedIndex = 0.obs;

  @override
  ready() async {
    _iniVM();
    await _loadDomainData();
    restoreSelections();
  }

  /// 初始化vm
  _iniVM() {
    register(FilterStateVM());
    register(FilterPreviewVM());
    register(SelectInputVM());

    filterStateVM = Get.find<FilterStateVM>();
    filterPreviewVM = Get.find<FilterPreviewVM>();
    selectInputVM = Get.find<SelectInputVM>();
  }

  /// 回显数据
  setChooseBackMaps(Map<String, Map<String, DomainInfoModel>>? choose) {
    chooseBackMaps = choose;
  }

  /// 加载筛选数据
  Future<void> _loadDomainData() async {
    List<DomainBean> domainList = await _repository.getDomainLists();
    for (var item in domainList) {
      if ((item.key == DisCons.YMGC || item.key == DisCons.TBGC)) {
        item.children = _processData(item.children);
      } else if (item.key == DisCons.SJLX) {
        item.children = _processRegistrationTimeData(item.children);
      }
    }

    /// 封装数据model
    List<BaseFilterItem> filters =
        FilterConverter.convertDomainBeans(domainList);

    for (var i = 0; i < filters.length; i++) {
      BaseFilterItem item = filters[i];
      Rx<DomainTitleModel> model = DomainTitleModel(
        name: item.title,
        key: item.key,
        selected: i == 0 ? true : false,
        state: 0,
      ).obs;

      /// 左边选择项
      domainTitles.add(model);

      /// 右侧数据
      filterStateVM.setChildCategories(item.key, item.children);

      /// 预览回显数据
      filterPreviewVM.selectedMaps.putIfAbsent(item.key, () => {});
    }
  }

  /// 选择左侧分类列表
  void selectedCategoryIndex(int index) {
    selectedIndex.value = index;
    domainTitles.refresh();
  }

  /// 刷新子列表数据
  void updateChildCategories() {
    domainTitles[selectedIndex.value].refresh();
  }

  /// 重置左边分类列表的星星
  void resetTitleState() {
    for (var model in domainTitles) {
      model.value = model.value.copyWith(state: 0);
      model.refresh();
    }
  }

  /// 重置所有
  void resetAll() {
    /// 清空预览的map集合
    filterPreviewVM.resettingMap();

    /// 重置所有选中状态
    filterStateVM.resetAllSelections();

    /// 清空所有input持有
    selectInputVM.resetAll();

    /// 刷新列表
    resetTitleState();
  }

  /// 添加选中数据
  addSelectMaps(
      {String? childKey,
      bool? sChoice,
      bool? isSelected,
      String? name,
      String? key,
      String? value}) {
    String parentKey = domainTitles[selectedIndex.value].value.key;
    filterPreviewVM.setSelectMaps(
        parentKey, sChoice, isSelected, childKey!, name!, key!, value);
    // 添加数据之后需要刷新列表项
    domainTitles.refresh();
  }

  /// 删除所选择的数据
  void deleteSelectedMap(String parentKey, String childKey) {
    filterPreviewVM.deleteSelectedMap(parentKey, childKey);
    filterStateVM.resetSelections(parentKey, childKey);
    // 删除数据之后需要刷新列表项
    domainTitles.refresh();
  }

  /// 回选数据解析
  /// 初始化恢复选中状态
  Future<void> restoreSelections() async {
    await Future.delayed(const Duration(milliseconds: 100));
    if (chooseBackMaps == null) {
      return;
    }
    filterPreviewVM.selectedMaps.value = chooseBackMaps!;

    filterStateVM.childCategories.forEach((categoryKey, items) {
      final selectedKeys =
          filterPreviewVM.selectedMaps[categoryKey]?.keys.toSet() ?? {};
      for (var item in items) {
        if (selectedKeys.contains(item.key)) {
          /// 选择框 处理
          if (item.type == DisCons.rangeSelector && item.key == DisCons.YMCD) {
            String value =
                filterPreviewVM.getSelectedValue(categoryKey, item.key);
            selectInputVM.initSelectedData(value);
          }
          final model = filterPreviewVM.selectedMaps[categoryKey]?[item.key];
          if (model == null) return;

          /// 自定义
          if (item.custom != null) {
            if ((item.custom?.key == model.childKey) &&
                model.key == DisCons.CUSTOM) {
              item.custom?.value = model.value;
            }
          }
          for (var data in item.children) {
            /// 多选
            if (model.value.contains(DisCons.SPLIT_S)) {
              final models = model.value.split(DisCons.SPLIT_S).toList();
              for (var s in models) {
                if (s == data.value) {
                  data.isSelected.value = true;
                  if (data.children.isNotEmpty) {
                    for (var child in data.children) {
                      if (child.children.isNotEmpty) {
                        for (var item in child.children) {
                          for (var m in models) {
                            if (m == item.value) {
                              item.isSelected.value = true;
                            }
                          }
                        }
                      }
                    }
                  }
                }
              }
            }

            /// 单选
            else {
              if (data.value == model.value) {
                data.isSelected.value = true;
              }
            }
          }
        }
      }
    });
    domainTitles.refresh();
  }

  /// 处理 域名构成和特殊构成数据
  List<DomainFilterChild> _processData(List<DomainFilterChild>? children) {
    if (children == null || children.isEmpty) return [];
    final originChild = children.first;
    final List<DomainFilterChild> result = [];
    DomainFilterChild? currentGroup;

    final unlimitedItem = originChild.data?.firstWhere(
      (item) => (item as Map).keys.first == DisCons.NO_LIMIT,
      orElse: () => null,
    );
    if (unlimitedItem != null) {
      result.add(DomainFilterChild(
        pid: originChild.pid,
        sort: originChild.sort,
        name: DisCons.NO_LIMIT,
        key: originChild.key,
        type: originChild.type,
        data: [unlimitedItem],
      ));
    }

    for (final item in originChild.data ?? []) {
      final entry = item as Map<String, dynamic>;
      final key = entry.keys.first;
      final value = entry.values.first.toString();

      if (value == "x") {
        currentGroup = DomainFilterChild(
          pid: originChild.pid,
          sort: originChild.sort,
          name: key,
          key: originChild.key,
          type: originChild.type,
          data: [],
        );
        result.add(currentGroup);
      } else if (currentGroup != null) {
        currentGroup.data?.add(item);
      }
    }
    return result;
  }

  /// 修改 注册时间数据
  List<DomainFilterChild> _processRegistrationTimeData(
      List<DomainFilterChild>? children) {
    if (children == null || children.isEmpty) return [];
    final year = DisTimeUtil.generateRegistrationYears();
    final customTime = DisTimeUtil.generateMonthEndPairs();
    final timeChild = DomainFilterChild(
        name: DisCons.CUSTOM,
        key: DisCons.SCSJ,
        type: DomainTypeEnum.S_CHOICE.value,
        data: customTime);
    final time = DisTimeUtil.generateDeletionDates(timeChild);
    for (var model in children) {
      if (model.key == DisCons.ZCSJ) {
        model.data = year;
      } else if (model.key == DisCons.SCSJ) {
        model.options = time;
      }
    }
    return children;
  }

  /// 监听检查选择框数据
  checkChildSelectValue(DomainTypeEnum domainType, String name,
      String? parentKey, String? childKey, String key, String keyValue) {
    if (selectInputVM.selectedFromValue.value > 0 &&
        selectInputVM.selectedToValue.value > 0) {
      filterPreviewVM.setSelectedMaps(
          domainType, name, parentKey, childKey, key, keyValue);
    }
  }
}
